package org.dromara.nursing.service.impl;

import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.dromara.nursing.domain.bo.MsAbilityAssessmentBo;
import org.dromara.nursing.domain.vo.MsAbilityAssessmentVo;
import org.dromara.nursing.domain.MsAbilityAssessment;
import org.dromara.nursing.mapper.MsAbilityAssessmentMapper;
import org.dromara.nursing.service.IMsAbilityAssessmentService;
import org.dromara.common.satoken.utils.LoginHelper;
import cn.dev33.satoken.stp.StpUtil;

import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 老年人能力评估Service业务层处理
 *
 * @author Lion Li
 * @date 2025-04-23
 */
@RequiredArgsConstructor
@Service
public class MsAbilityAssessmentServiceImpl implements IMsAbilityAssessmentService {

    private final MsAbilityAssessmentMapper baseMapper;
    
    // 定义角色常量
    private static final String NURSE_ROLE_KEY = "nurse";
    private static final String ADMIN_ROLE_KEY = "admin_ms";
    private static final String SUPER_ADMIN_ROLE_KEY = "admin";

    /**
     * 查询老年人能力评估
     *
     * @param id 主键
     * @return 老年人能力评估
     */
    @Override
    public MsAbilityAssessmentVo queryById(Long id){
        MsAbilityAssessmentVo vo = baseMapper.selectVoById(id);
        
        // 基于角色的数据权限过滤
        boolean isNurseUser = StpUtil.hasRole(NURSE_ROLE_KEY);
        boolean isAdminUser = StpUtil.hasRole(ADMIN_ROLE_KEY) || StpUtil.hasRole(SUPER_ADMIN_ROLE_KEY);
        
        // 如果是护理员用户，只能查看自己录入的记录
        if (isNurseUser && !isAdminUser && vo != null) {
            Long userId = LoginHelper.getUserId();
            // 通过MsAbilityAssessment实体获取createBy值
            MsAbilityAssessment entity = baseMapper.selectById(id);
            
            // 如果用户ID为null或createBy为null，或者两者不相等，则没有权限
            if (userId == null || entity == null || entity.getCreateBy() == null || !userId.equals(entity.getCreateBy())) {
                return null;
            }
        }
        
        return vo;
    }

    /**
     * 分页查询老年人能力评估列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 老年人能力评估分页列表
     */
    @Override
    public TableDataInfo<MsAbilityAssessmentVo> queryPageList(MsAbilityAssessmentBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<MsAbilityAssessment> lqw = buildQueryWrapper(bo);
        Page<MsAbilityAssessmentVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的老年人能力评估列表
     *
     * @param bo 查询条件
     * @return 老年人能力评估列表
     */
    @Override
    public List<MsAbilityAssessmentVo> queryList(MsAbilityAssessmentBo bo) {
        LambdaQueryWrapper<MsAbilityAssessment> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<MsAbilityAssessment> buildQueryWrapper(MsAbilityAssessmentBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<MsAbilityAssessment> lqw = Wrappers.lambdaQuery();
        lqw.orderByDesc(MsAbilityAssessment::getId);  // 按ID倒序，最新记录在前
        lqw.like(StringUtils.isNotBlank(bo.getElderName()), MsAbilityAssessment::getElderName, bo.getElderName());
        
        // 基于角色的数据权限过滤
        boolean isNurseUser = StpUtil.hasRole(NURSE_ROLE_KEY);
        boolean isAdminUser = StpUtil.hasRole(ADMIN_ROLE_KEY) || StpUtil.hasRole(SUPER_ADMIN_ROLE_KEY);
        
        // 如果是护理员用户，只能查看自己录入的记录
        if (isNurseUser && !isAdminUser) {
            Long userId = LoginHelper.getUserId();
            if (userId != null) {
                // 使用实体类的createBy字段过滤，确保类型一致
                lqw.eq(MsAbilityAssessment::getCreateBy, userId);
            }
        }
        
        return lqw;
    }

    /**
     * 新增老年人能力评估
     *
     * @param bo 老年人能力评估
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(MsAbilityAssessmentBo bo) {
        MsAbilityAssessment add = MapstructUtils.convert(bo, MsAbilityAssessment.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改老年人能力评估
     *
     * @param bo 老年人能力评估
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(MsAbilityAssessmentBo bo) {
        MsAbilityAssessment update = MapstructUtils.convert(bo, MsAbilityAssessment.class);
        validEntityBeforeSave(update);
        
        // 基于角色的数据权限过滤
        boolean isNurseUser = StpUtil.hasRole(NURSE_ROLE_KEY);
        boolean isAdminUser = StpUtil.hasRole(ADMIN_ROLE_KEY) || StpUtil.hasRole(SUPER_ADMIN_ROLE_KEY);
        
        // 如果是护理员用户，只能修改自己录入的记录
        if (isNurseUser && !isAdminUser) {
            Long userId = LoginHelper.getUserId();
            MsAbilityAssessment original = baseMapper.selectById(update.getId());
            
            if (original != null && original.getCreateBy() != null) {
                if (!userId.equals(original.getCreateBy())) {
                    return false;  // 非本人创建的记录不允许修改
                }
            }
        }
        
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(MsAbilityAssessment entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除老年人能力评估信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        
        // 基于角色的数据权限过滤
        boolean isNurseUser = StpUtil.hasRole(NURSE_ROLE_KEY);
        boolean isAdminUser = StpUtil.hasRole(ADMIN_ROLE_KEY) || StpUtil.hasRole(SUPER_ADMIN_ROLE_KEY);
        
        // 如果是护理员用户，只能删除自己录入的记录
        if (isNurseUser && !isAdminUser) {
            Long userId = LoginHelper.getUserId();
            for (Long id : ids) {
                MsAbilityAssessment record = baseMapper.selectById(id);
                if (record != null && record.getCreateBy() != null) {
                    if (!userId.equals(record.getCreateBy())) {
                        return false;  // 存在非本人创建的记录，不允许删除
                    }
                }
            }
        }
        
        return baseMapper.deleteByIds(ids) > 0;
    }
}
